//
//  DDSend_to_friend_circle.m
//  dingdang
//
//  Created by mac mini on 16/1/14.
//  Copyright © 2016年 丁当科技. All rights reserved.
//

#import "DDSend_to_friend_circle.h"
//#import "DDQuestionsRootTableViewCell.h"
#import "DDSend_friend_circle_cell.h"
#import "DDTypeDefine.h"
#import "PECropViewController.h"
#import "DDNetWorkAPIClient.h"
#import "JSONKit.h"

#define Encryption_TAG 1001
#define Reward_TAG 1002
#define Help_TAG 1003
#define RGB(R,G,B)		[UIColor colorWithRed:R/255.0f green:G/255.0f blue:B/255.0f alpha:1.0f]

@interface DDSend_to_friend_circle ()<UITextViewDelegate,UIPickerViewDataSource,UIPickerViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,PECropViewControllerDelegate,UIGestureRecognizerDelegate>
{
    NSMutableArray * array_picker;
    NSString * paramString_body;
    DDType_Question_QuestionPublishType paramFlagNumber_chooseType;
    DDType_Question_QuestionType paramFlag_questionType;
    DDType_Question_QuestionType flag_questionOptionSetForQuestionType;
    NSString * param_score;
    CGRect holdRect_contentOfChoose;
    BOOL flagShow_contentOfChoose;
    UINavigationController * photoProcessNav;
    UIImage * paramImage_process;
    NSString * paramImageString_process;
    NSMutableArray * paramImage_array;
    NSMutableArray * paramImageString_array;
    NSMutableDictionary * hold_paramProcessDic;
    BOOL isCleanTableView;
    NSMutableDictionary * m_temp_oldDic;
    NSMutableDictionary * paramDic;
    int uploadImg_num;
    
}
@property (weak, nonatomic) IBOutlet UILabel *shaishai_Lable;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *contentOfPickerView;
@property (weak, nonatomic) IBOutlet UIPickerView *picker_choose;
@end

@implementation DDSend_to_friend_circle
- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"进入到------------>DDSend_to_friend_circle");
    // Do any additional setup after loading the view from its nib.
    [self createUI];
    [self createData];
    //[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(publishSuccess) name:@"publishSuccess" object:nil];
}
//-(void)publishSuccess{
//    NSLog(@"发布成功！");
//    //[self btnEncryptionClick:nil];
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)createUI
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBarHidden = YES;
    
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.backgroundColor = RGB(245, 245, 245);
    //[self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([DDQuestionsRootTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"questionCell"];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([DDSend_friend_circle_cell class]) bundle:nil] forCellReuseIdentifier:@"friend_circle_cell"];
    [self addNavigatorTitle:NSLocalizedString(@"写晒晒", nil) parent:self.view];
    self.barViewControl.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"top_Background"]];
    [self AddLeftBtnAction:nil normal:@"top_返回" selected:@"top_返回" action:^{
        [self dismissViewControllerAnimated:YES completion:nil];
        //[self.navigationController popViewControllerAnimated:YES];
    }];
    [self AddRightBtnAction:@"发布" normal:@"" selected:@"'" action:^{
        [self overAction:nil];
    }];
    //    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissPopup)];
    //    tapRecognizer.numberOfTapsRequired = 1;
    //    tapRecognizer.delegate = self;
    //    [self.view addGestureRecognizer:tapRecognizer];
    paramFlagNumber_chooseType = DDType_question_questionPublishType_help;
    param_score = 0;
    paramFlag_questionType = DDType_question_questionType_JianDaTi;
    paramImage_process = nil;
    paramImageString_process = @"";
    paramString_body = @"";
    m_temp_oldDic = nil;
    
}

-(void)createData{
    //    paramFlagNumber_chooseType = DDType_question_questionPublishType_Encryption;
    
    paramDic = [[NSMutableDictionary alloc]init];
    flagShow_contentOfChoose = NO;
    array_picker = [NSMutableArray array];
    //    [array_picker addObjectsFromArray:QuestionTypeArray];
    [self.picker_choose reloadAllComponents];
    //    paramFlag_questionType = DDType_question_questionType_DanXuanTi;
    hold_paramProcessDic = [NSMutableDictionary dictionary];
    paramImageString_array = [NSMutableArray array];
    paramImage_array = [NSMutableArray array];
    uploadImg_num = 0;
    //self.tableView.tableFooterView = [self createFootView];
}


#pragma mark -UITableDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
//-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
//{
//    t
//    return 114;
//}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0) {
        float height = 180;//220;
        //        if (paramImage_process) {
        //            height += 70;
        //        }
        //if (paramImage_array.count>0) {
            height += (tableView.frame.size.width-10)/4 * (paramImage_array.count/4+1);
//        }else{
//        
//        }
        return height;
    }
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"friend_circle_cell";
    DDSend_friend_circle_cell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    //static NSString *identifier = @"questionCell";
    //DDQuestionsRootTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    
    [cell clean:cell withImageArray:paramImage_array];
    NSLog(@"paramImage_array=================>>>%@",paramImage_array);
    if (indexPath.row == 0) {
        cell.info_thisCellType = cellType_questionType_body;
        cell.textView_body.text = paramString_body;
        
        [cell.textView_body addTextViewEndEvent:^(PlaceholderTextView *text) {
            paramString_body = text.text;
        }];
    }
    cell.info_delegate = self;
    cell.uploadImg_num = uploadImg_num;
    [cell fixCell:cell withImageArray:paramImage_array];
    
    return cell;
}

//- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    DDQuestionsRootTableViewCell * cell = (DDQuestionsRootTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
//
//    return indexPath;
//}

#pragma mark - picker dataSource & delegate
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return array_picker.count;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return array_picker[row];
}


-(float) xPostiong:(UIView *)view sp:(float)sp
{
    return view.frame.size.width+view.frame.origin.x + sp;
}

-(float) yPostiong:(UIView *)view sp:(float)sp
{
    return view.frame.size.height+view.frame.origin.y + sp;
}

//#pragma makr - private
//-(void)HelpAction:(UIButton *)sender
//{
//    sender.selected = YES;
//    
//    UIButton *EncryptionButton = (UIButton*)[sender.superview viewWithTag:Encryption_TAG];
//    EncryptionButton.selected = NO;
//    UIButton *RewardButton = (UIButton*)[sender.superview viewWithTag:Reward_TAG];
//    RewardButton.selected = NO;
//}

//结束出题
-(void)overAction:(UIButton *)sender
{
    //此处出题上传服务器
    BOOL isCanSave = [self assemblyDic];
    if (isCanSave == NO) {
        return;
    }
    //[self showHUD:@"正在发布..."];
    DDNetWorkAPIClient * client = [[DDNetWorkAPIClient alloc]init];
    NSDictionary * dic = @{@"data" : [hold_paramProcessDic JSONString]};
    [client mainQuestionSave:dic completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
        
        
        //        if (isSuccess == 1 && [message isEqualToString:@"成功"] ) {
        //            DDQuestionBaseInfoViewController * baseInfo = [[DDQuestionBaseInfoViewController alloc]init];
        //            baseInfo.info_publishType = paramFlagNumber_chooseType;
        //            baseInfo.info_questions = @[object];
        //            baseInfo.hidesBottomBarWhenPushed = YES;
        //            [self.navigationController pushViewController:baseInfo animated:YES];
        //        }else{
        NSArray *questions_array = [[NSArray alloc] initWithObjects:object, nil];
        [paramDic setObject:questions_array forKey:@"questions"];
        [paramDic setObject:@"0" forKey:@"type"];
        //[self delayHUD:message];
        [self saveQuestionAndTopicSave];
        //        }
        //[self hideHUD];
        [self cleanParam];
        isCleanTableView = YES;
        [self.tableView reloadData];
    }];
}
-(BOOL)assemblyDic{
    
    [hold_paramProcessDic removeAllObjects];
    
    for (int i = 0; i < self.tableView.visibleCells.count; i++) {
        //DDQuestionsRootTableViewCell * cell = self.tableView.visibleCells[i];
        DDSend_friend_circle_cell * cell = self.tableView.visibleCells[i];
        [cell.textView_body resignFirstResponder];
        if (cell.info_thisCellType == cellType_questionType_setRewardPoint) {
            [hold_paramProcessDic setObject:[NSNumber numberWithDouble:cell.tf_rewardPoint.text.doubleValue] forKey:@"score"];
        }
    }
    [hold_paramProcessDic setObject:[NSNumber numberWithInteger:paramFlag_questionType] forKey:@"type"];
    NSMutableArray * bodyArray = [NSMutableArray array];
    
    
    if (paramString_body.length > 0) {
        [bodyArray addObject:@{
                               @"type" : @"TEXT",
                               @"text" : paramString_body,
                               }];
    }else{
        if (paramFlagNumber_chooseType == DDType_question_questionPublishType_Encryption && (paramFlag_questionType == DDType_question_questionType_DanXuanTi||paramFlag_questionType == DDType_question_questionType_DuoXuanTi||paramFlag_questionType == DDType_question_questionType_PanDuanTi)) {
            
            
        }else{
            [self delayHUD:@"请填写内容"];
            return NO;
        }
        
    }
    for (int i=0; i<paramImageString_array.count; i++) {
        if (paramImageString_process.length > 0) {
            [bodyArray addObject:@{
                                   @"type" : @"IMAGE",
                                   @"url" : paramImageString_array[i],
                                   }];
        }
    }
    [hold_paramProcessDic setObject:bodyArray forKey:@"body"];//增加数组元素
    
    return YES;
}

-(void)saveQuestionAndTopicSave{
    
    BOOL canPublish = [self assemblyDic];
    if (canPublish == NO) {
        return;
    }
    DDNetWorkAPIClient * client = [[DDNetWorkAPIClient alloc]init];
    
    [client queryIntegral:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
        if (isSuccess) {
            NSInteger  intgeral = [[dict objectForKey:@"integral"] integerValue];
            NSInteger  fillIntgeral = [[paramDic objectForKey:@"reward"] integerValue];
            
            NSInteger number = [[paramDic objectForKey:@"maxRewardNumber"] integerValue];
            if (number <= 0) {
                number = 1;
            }
            if (fillIntgeral*number<=intgeral) {
                //[self showHUD:@"晒晒正在发布..."];
                
                [client mainTopicSave:paramDic completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
                   
                    if ([message isEqualToString:@"成功"]) {
                        //NSLog(@"发晒晒成功！");
                        //[self hideHUD];
                        [self delayHUD:@"晒晒发布成功"];
                        [paramImage_array removeAllObjects];
                        [paramImageString_array removeAllObjects];
                        [hold_paramProcessDic removeAllObjects];
                        [self.tableView reloadData];
                        uploadImg_num = 0;
                        
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"reload" object:nil];

                        [self dismissViewControllerAnimated:YES completion:nil];
                        
                        
                    }else{
                        //[self delayHUD:message];
                    }
                }];
                //[self hideHUD];
            }else{
                [self delayHUD:@"您的积分不足"];
            }
            
            
        }
    }];
}

-(void)cleanParam{
    paramImage_process = nil;
    paramImageString_process = @"";
    paramString_body = nil;
    m_temp_oldDic = nil;
    
}

//-(UIView *)createFootView{
//    UIView * footView =[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, CGRectGetWidth([[UIScreen mainScreen] bounds]), 114)];
//    NSLog(@"self.shaishai_Lable.frame==========%@",NSStringFromCGRect(self.shaishai_Lable.frame));
//    UIButton * btnNextStep = [UIButton buttonWithType:UIButtonTypeCustom];
//    btnNextStep.frame = CGRectMake(CGRectGetMidX([[UIScreen mainScreen] bounds]) - 40, 15, 80, 40);
//    [btnNextStep setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [btnNextStep setTitle:@"发布晒晒" forState:UIControlStateNormal];
//    [btnNextStep setBackgroundColor:RGB(46,187,232)];
//    [btnNextStep addTarget:self action:@selector(overAction:) forControlEvents:UIControlEventTouchUpInside];
//    btnNextStep.titleLabel.font = [UIFont fontWithName:@"Arial" size:17.0];
//    [btnNextStep setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
//    [btnNextStep setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
//    btnNextStep.layer.cornerRadius = 5;
//    btnNextStep.layer.masksToBounds = YES;
//    [footView addSubview:btnNextStep];
//    NSLog(@"btnNextStep.frame====%@",NSStringFromCGRect(btnNextStep.frame));
//    NSLog(@"footView.frame====%@",NSStringFromCGRect(footView.frame));
//    return footView;
//}

//
//- (IBAction)btnHelpClick:(id)sender {
//    paramFlagNumber_chooseType = DDType_question_questionPublishType_help;
//
//
//    param_score = 0;
//    paramFlag_questionType = DDType_question_questionType_JianDaTi;
//    paramImage_process = nil;
//    paramImageString_process = @"";
//    paramString_body = @"";
//
//    m_temp_oldDic = nil;
//
//    [self hiddenChooseContent];
//
//
//    self.btn_encryption.selected = NO;
//    self.btn_help.selected = YES;
//    self.btn_reward.selected = NO;
//    [self.tableView reloadData];
//    self.tableView.tableFooterView = [self createFootView];
//
//}


-(void)showChooseContent{
    
    
    if (holdRect_contentOfChoose.origin.y == 0) {
        holdRect_contentOfChoose = self.contentOfPickerView.frame;
    }
    if (flagShow_contentOfChoose == NO) {
        flagShow_contentOfChoose = YES;
        [UIView animateWithDuration:.3 animations:^{
            self.contentOfPickerView.frame = CGRectMake(CGRectGetMinX(self.contentOfPickerView.frame),
                                                        CGRectGetMinY(self.contentOfPickerView.frame) - CGRectGetHeight(self.contentOfPickerView.frame),
                                                        CGRectGetWidth(self.contentOfPickerView.frame),
                                                        CGRectGetHeight(self.contentOfPickerView.frame));
        } completion:^(BOOL finished) {
            
        }];
    }
    
    NSLog(@"-(void)showChooseContent{self.contentOfPickerView.frame====%@",NSStringFromCGRect(self.contentOfPickerView.frame));
    
}

-(void)hiddenChooseContent{
    if (flagShow_contentOfChoose == YES) {
        flagShow_contentOfChoose = NO;
        [UIView animateWithDuration:.3 animations:^{
            self.contentOfPickerView.frame = holdRect_contentOfChoose;
        } completion:^(BOOL finished) {
            
        }];
    }
    NSLog(@"-(void)hiddenChooseContent{self.contentOfPickerView.frame====%@",NSStringFromCGRect(self.contentOfPickerView.frame));
}

-(void)openCamera{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.delegate = self;
        picker.allowsEditing = YES;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

-(void)openPhotoLib{
    
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        picker.delegate = self;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

- (IBAction)openEditor:(id)sender
{
    PECropViewController *controller = [[PECropViewController alloc] init];
    controller.delegate = self;
    controller.image = paramImage_process;
    
    UIImage *image = paramImage_process;
    CGFloat width = image.size.width;
    CGFloat height = image.size.height;
    CGFloat length = MIN(width, height);
    controller.imageCropRect = CGRectMake((width - length) / 2,
                                          (height - length) / 2,
                                          length,
                                          length);
    
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:controller];
    
    [self presentViewController:navigationController animated:YES completion:nil];
}



#pragma mark - pickerImage Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    paramImage_process = image;
    [self.tableView reloadData];
    [picker dismissViewControllerAnimated:YES completion:^{
        [self openEditor:nil];
    }];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -  PECropViewControllerDelegate
- (void)cropViewController:(PECropViewController *)controller didFinishCroppingImage:(UIImage *)croppedImage{
    [controller dismissViewControllerAnimated:YES completion:nil];
    
    paramImage_process = croppedImage;
    
    //此处是上传图片的请求
    DDNetWorkAPIClient * networkClient = [[DDNetWorkAPIClient alloc]init];
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    
    NSData * imageData = UIImageJPEGRepresentation(croppedImage, 0.1);
    NSString * imageString = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];//base64Encoding];
    
    [param setObject:imageString forKey:@"data"];
    [param setObject:@"jpg" forKey:@"extName"];
    [self showHUD:[NSString stringWithFormat:@"正在处理第%d张图片",uploadImg_num+1]];
    [networkClient uploadImage:param completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
        [self hideHUD];
        if ([[object objectForKey:@"code"] integerValue] == 0) {
            if ([object objectForKey:@"data"]) {
                paramImageString_process = [object objectForKey:@"data"];
                paramImage_process = croppedImage;
                [paramImageString_array addObject:paramImageString_process];
                [paramImage_array addObject:paramImage_process];
                NSLog(@"paramImage_array=======%@",paramImage_array);
                uploadImg_num++;
                [self.tableView reloadData];
            }
        }
        
    }];
    
    //http://dd5s.oss-cn-shenzhen.aliyuncs.com/upload/img/201507/201507152249266077.jpg
    
}

- (void)cropViewControllerDidCancel:(PECropViewController *)controller{
    [controller dismissViewControllerAnimated:YES completion:nil];
}

-(void)dismissPopup
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

#pragma mark - DDQuestionAnswerOptionSetViewControllerDelegate

-(void)DDQuestionAnswerOptionSetFinish:(NSMutableDictionary *)dic{
    m_temp_oldDic = dic;
    //[hold_paramProcessDic setValuesForKeysWithDictionary:dic];
}

@end
